<template>
  <section class='f-change-phone'>
    <van-form ref="ruleFormRef" @submit="onSubmit" input-align="right" error-message-align="right">
      <van-cell-group>
        <van-field v-model="userInfo.account" clearable name="account" label="当前号码" placeholder="请输入当前号码" readonly
          :rules="[{ required: true, message: '请填写当前号码' }]" />

        <van-field v-model="form.newPhone" clearable name="newPhone" label="更改号码" placeholder="请输入更改号码" type="tel" maxlength="11"
          :rules="[{ required: true, message: '请填写更改号码' },{ pattern: /^1[3-9]\d{9}$/, message: '请填写正确的手机号码'}]">
          <template #button>
            <van-button size="small" type="warning" @click="getMsgCodeHandle">{{count? count + '秒': '获取验证码'}}</van-button>
          </template>
        </van-field>

        <van-field v-model="form.verificationCode" clearable name="verificationCode" label="验证码" placeholder="请输入验证码" type="tel"
          maxlength="6" :rules="[{ required: true, message: '请填写验证码' }]" />

        <van-field v-model="form.password" clearable name="password" label="密码验证" placeholder="请输入密码"
          :type="form.showPassword?'':'password'" :rules="[{ required: true, message: '请填写密码' }]">
          <template #right-icon>
            <van-icon v-show="!form.showPassword" name="closed-eye" @click="form.showPassword = true" />
            <van-icon v-show="form.showPassword" name="eye-o" @click="form.showPassword = false" />
          </template>
        </van-field>
      </van-cell-group>

      <p class="f-tip">温馨提示：更换手机号后，下次登录请使用新的手机号码登录。</p>
      <div class="f-submit-btn">
        <van-button round block type="primary" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import { getStore, phoneFormat, successDeal } from '@/utils/utils';
import hexMD5 from "@/utils/md5.min.js"
import { showDialog } from 'vant';
import api from '../api'

export default {
  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const ruleFormRef = ref()

    const state = reactive({
      userInfo: {},
      form: {},

      counter: 0, // 计时器
      count: 0,
    })

    onMounted(() => {
      store.commit("setNavBar", {
        title: '更换手机号码',
        show: true,
        left: true,
        leftType: 'back',
        right: false,
        rightType: 'search',
      });

      state.userInfo = getStore('USER_INFO_MF')
      state.userInfo.account = phoneFormat(state.userInfo.account)
    })

    // 获取短信验证码
    const getMsgCodeHandle = () => {
      if (state.count) return
      ruleFormRef.value.validate(['newPhone']).then(res => {
        state.count = 120;
        countDown();

        let json = {
          phone: state.form.newPhone,
          source: 1,
          type: 3, // 1-注册，2-找回密码 3-修改手机号
        }
        api.getMsgCode(json).then((res) => {
          if (res) {
            successDeal('短信已发送！')
          }
        }).catch(err => {
          state.count = 0
          clearCounter()
        })
      })
    }

    //计时
    const countDown = () => {
      let count = state.count;

      clearCounter();
      state.counter = setInterval(() => {
        count--;
        state.count = count;
        if (count == 0) {
          clearCounter();
        }
      }, 1000);
    }

    //清除定时器
    const clearCounter = () => {
      clearInterval(state.counter);
    }

    const onSubmit = () => {
      let data = JSON.parse(JSON.stringify(state.form))
      let json = {
        "newPhone": data.newPhone,
        "password": hexMD5(data.password),
        "source": 1,
        "verificationCode": data.verificationCode
      }
      api.updatePhone(json).then(res => {
        showDialog({
          title: '提示',
          message: '更换手机号成功，请重新登录！',
        }).then(() => {
          router.replace('/')
        });
      })
    }

    return {
      ...toRefs(state),
      ruleFormRef,
      onSubmit,
      getMsgCodeHandle,
    }
  }
}
</script>
<style lang='scss' scoped>
.f-change-phone {
  .f-tip {
    font-size: 12px;
    color: #ff5c5c;
    padding: 10px 17px;
  }
  .f-submit-btn {
    margin-top: 70px;
    padding: 0 62px;
  }
}
</style>